define(['moment', 'jqplot-bar', 'jqplot-pointLabels', 'jqplot-pie', 'module/system/service/WatchDogService'], function (moment) {
    return ['$rootScope', '$scope', '$filter', '$stateParams', 'config', 'MMWService', '$compile', '$timeout', '$mdlToast', '$mdDialog', 'WatchDogService',
        function ($rootScope, $scope, $filter, $stateParams, config, $MMWService, $compile, $timeout, $mdlToast, $mdDialog, $WatchDogService) {
            var _refresh, dog, _collection = 'N', _report_style, _condition=[];
            // 20211222 modify by Alan for M#0104310: 新增分組排序
            var groupSort = {};
            // 20211228 modify by Alan for M#0104310: 新增自然排序
            const collator = new Intl.Collator('en', { numeric: true, sensitivity: 'base' });
            var naturalComparator = function(a, b) {
                return ('value' in a) ? collator.compare(a.value, b.value) : collator.compare(a, b) 
            };
            $scope.init = function(){
                $scope.tab_size = 1;
                $scope.tab_info = [];
                $scope.tab_result = {};
                $scope.$root.currentState = $stateParams.data.report_id;
                $scope.title = $stateParams.data.report_name;
                const initCondition = $stateParams.data.condition || [];
            	// 20230328 modify by Alan for M#0122582 - 公司名稱
                $rootScope.companyName = config.cache.sys_parameter.CompanyName || '';

                // R51 成品序號追溯 - 在質量追溯模組裡
                if($scope.title === 'R51.title') {
                    $scope.title = $filter('translate')($scope.title);
                }

                $scope.queryMode = 'list';
                //20191226 modify by Dustdusk for M#: 增加自動更新功能
                _refresh = {
                    condition:[],
                    count:0,
                    time:60,
                    page_time:30,
                    is_start:'N',
                    page_count:25,
                    line_height:32,
                    font_size:14
                };
                //20200331 69092 每張報表都要有自己的localstorage 取得localstorage modify by 韋齊
                var _s_refresh = localStorage.getItem(config.appName + '_RPT_Settings_'+$scope.$root.currentState);
                if(_s_refresh){
                    _refresh = angular.merge(_refresh, JSON.parse(_s_refresh));
                    //_refresh.distance = Math.ceil((_refresh.page_count/_refresh.page_time * (_refresh.font_size+18))*_refresh.sleep);
                    $scope.conditionList = _refresh.condition;
                }
                _refresh.sleep = 0.2;
                _refresh.font_size = parseInt(_refresh.font_size);
                _refresh.count = 0;
                _refresh.row_count = 0 - _refresh.page_time / _refresh.sleep;

                dog = {
                    sleep:_refresh.sleep,
                    bark:function(feed, next){
                        var _result_list = document.getElementById('result_list'),
                            _page_config = $scope.PageConfig;
                        if(_collection == 'Y'){
                            _result_list = document.getElementById('tab_'+ $scope.select_tab + '_result_list');
                            _page_config = $scope['tab_'+$scope.select_tab].PageConfig;
                        }

                        if(_refresh.count >= _refresh.time){
                            _refresh.count = 0;
                            $scope.search(_condition, next, false);
                        } else {
                            var _distance = Math.ceil((_result_list.scrollHeight- _result_list.offsetHeight) / _refresh.page_time *_refresh.sleep);
                            if(_distance>0 && _refresh.row_count < 0){
                                //當需要滾動的時候，則不需要預先等待時間
                                _refresh.row_count = 0;
                            } else if(_distance == 0){
                                _distance = 1;
                            }

                            if(_refresh.row_count>0){
                                var _old_height = _result_list.scrollTop;
                                _result_list.scrollTop = _refresh.row_count;
                                if(_old_height == _result_list.scrollTop){
                                    _refresh.row_count= 0 - _refresh.page_time / _refresh.sleep; //換頁後delay一段時間才會開始跑(Ex.10*1*0.2 = 2秒後執行)
                                    _result_list.scrollTop = 0;
                                    if((_page_config.page+1)>(_page_config.total_page-1)){
                                        //回到第一頁
                                        _page_config.page = 0;
                                    } else {
                                        $scope.nextPage(_page_config);
                                    }
                                    $timeout(function(){
                                        next();
                                    });
                                } else {
                                    next();
                                }
                            } else {
                                next();
                            }
                            _refresh.row_count+= _distance;
                            _refresh.count+= dog.sleep;
                        }
                    }
                };

                if(window.nodeRequire)
                    $scope.can_export = true;

                userCustomReportFormatGet($stateParams.data.report_id, function(){
                    if(_refresh.is_start == 'Y'){
                        $scope.isClose = true;
                        $scope.beforeSearch({
                            callback: function(){
                                $WatchDogService.startWatch(dog, true);
                            }
                        });
                    }
                    initSearch(initCondition, () => {});
                });
            };

            // 20230720 modify by alan for M#140870: 報表新開窗自動代入參數查詢功能
            function initSearch(condition, callback) {
                // for $rootScope.OpenProgramWindow()
                // 20231116 modify by alan for M#140870: 修正報表新開窗自動代入參數查詢功能判斷條件
                if ($rootScope.isElectron && condition.length === 0) {
                    const ipcRenderer = window.nodeRequire('electron').ipcRenderer;
                    // 作業就緒，通知主程序
                    ipcRenderer.send('isReady');
                    // 監聽主程序的訊息，取得參數後進行查詢
                    ipcRenderer.once('parameters', (event, args) => {
                        let { condition } = JSON.parse(args)
                        if($scope.checkCondition(condition)) {
                            $scope.search(condition, function(){
                                $scope.$root.hideLoading();
                                if(typeof callback === 'function') {
                                    callback();
                                }
                            }, false);
                        }
                    });
                // for $rootScope.changeProgram()
                } else if(condition.length > 0 && $scope.checkCondition(condition)){
                    $scope.search(condition, function(){
                        $scope.$root.hideLoading();
                        if(typeof callback === 'function') {
                            callback();
                        }
                    }, false);
                }
            }

            $scope.back = function(){
                $scope.final(function(){
                    $scope.$root.hideMenu();
                    // 20230222 modify by Alan for M#0128751: 配合報表新開視窗功能調整
                    if(config.setting.externalWindow === 'Y') {
                        $rootScope.closeCurrentWindow();
                    } else {
                        $scope.$root.changeProgram('home', true);
                    }
                });
            };

            $scope.final = function(callback){
                if($WatchDogService.isStart){
                    $WatchDogService.stopWatch();
                }
                if(typeof callback === 'function')
                    callback();
            }

            $scope.search = function(condition, next, showLoading){
                //20200514 add by Dustdusk for M#: 增加儲存
                _refresh.condition = $scope.conditionList;
                localStorage.setItem(config.appName + '_RPT_Settings_'+$scope.$root.currentState, JSON.stringify(_refresh));
                _condition = condition;
                if(_collection == 'Y'){
                    var _tab_count = 0;
                    $scope.tab_info.forEach(function(tab, index){
                        var _conditoin = [],
                            query_condition_info = tab.query_condition_info;//子報表的查詢條件
                        if(query_condition_info && query_condition_info.length>0){
                            query_condition_info.forEach(function(condition_info){
                                //查詢條件內取出符合子報表使用的查詢條件
                                var _temps = $filter('filter')(condition, {column_name:condition_info.query_column}, true);
                                _temps.forEach(function(_temp){
                                    _conditoin.push({
                                          //column_name 轉換成子報表用的欄位
                                          column_name: condition_info.query_condition,
                                          query_mode: _temp.query_mode,
                                          merge_condition_model: _temp.merge_condition_model,
                                          value: _temp.value
                                    });
                                });
                            });
                        } else {
                            _conditoin = condition;
                        }
                        userCustomReportDataGet(tab.report_id, _conditoin, function(data){
                            $scope.tab_result[index] = data.report_data;
                            $scope['tab_'+index].statistics_result = data.report_statistics;
                            if(_tab_count == $scope.tab_info.length){
                                if(next)
                                    next();
                            } else {
                                _tab_count++;
                            }
                        }, next, showLoading == undefined);
                    });
                } else {
                    userCustomReportDataGet($stateParams.data.report_id, condition, undefined, next, showLoading==undefined);
                }
            };

            $scope.export = function(){
                var condition = $rootScope.genConditioninfo();
                exportExcel($stateParams.data.report_id, condition);
            };

            $scope.getPages = function(list, PageConfig, filterItem, header){
                resetFilter(filterItem);
                if(list){
                    var temp_list = $filter('filter')(list, filterItem)
                    if(header){
                        temp_list = $filter('orderBy')(temp_list, "'"+header.code+"'", header.order, naturalComparator);
                    }
                    if(PageConfig){
                        PageConfig.page = PageConfig.page||0;
                        PageConfig.total_page = Math.ceil(temp_list.length/PageConfig.page_count);
                        if(PageConfig.page >= PageConfig.total_page){
                            PageConfig.page = 0;
                        }
                        var index = PageConfig.page*PageConfig.page_count;
                        return temp_list.slice(index, index+PageConfig.page_count);
                    } else {
                        return temp_list;
                    }
                } else {
                    PageConfig.page = 0;
                    PageConfig.total_page = 1;
                    return list;
                }
            };

            $scope.getGroupPages = function(groupList, PageConfig, filterItem, header){
                resetFilter(filterItem);
                if(groupList){
                    var total_record = 0,
                        temp_groupList = [];
                    var start_index = PageConfig.page*PageConfig.page_count;
                    var end_index = start_index + PageConfig.page_count;
                    for(var i=0;i <groupList.length;i++){
                        var temp_list = $filter('filter')(groupList[i].result, filterItem);
                        if(total_record<end_index && (total_record+temp_list.length)>start_index){
                            groupList[i].$start_index = start_index-total_record;
                            groupList[i].$end_index = end_index-total_record;
                            //還沒加之前小於end 就表示這筆群組在範圍內
                            temp_groupList.push(groupList[i]);
                        }
                        if(!groupList[i].is_close)
                            total_record += temp_list.length;
                    }
                    if (header && (header.code in temp_groupList[0])){
                        groupSort = header;
                        temp_groupList = $filter('orderBy')(temp_groupList, "'"+header.code+"'", header.order, naturalComparator);
                    } else if(groupSort) {
                        temp_groupList = $filter('orderBy')(temp_groupList, "'"+groupSort.code+"'", groupSort.order, naturalComparator);
                    }

                    PageConfig.total_page = Math.ceil(total_record/PageConfig.page_count);
                    PageConfig.page = PageConfig.page||0;
                    if(PageConfig.page >= PageConfig.total_page){
                        PageConfig.page = 0;
                    }
                    return temp_groupList;
                } else {
                    PageConfig.page = 0;
                    PageConfig.total_page = 1;
                    return groupList;
                }
            };

            $scope.getGroupResult = function(groupItem, filterItem, header){
                resetFilter(filterItem);
                if(groupItem.result){
                    if(groupItem.is_close == true){
                        return [];
                    } else {
                        var temp_list = $filter('filter')(groupItem.result, filterItem);
                        if(header) {
                            temp_list = $filter('orderBy')(temp_list,  "'"+header.code+"'", header.order, naturalComparator);
                        }
                        var index = groupItem.$start_index<0?0:groupItem.$start_index;
                        return temp_list.slice(index,+groupItem.$end_index);
                        //return $filter('filter')(groupItem.result, filterItem);
                    }
                } else {
                    return groupItem.result;
                }
            };

            $scope.orderResult = function(index, key){
                if(key != undefined){
                    if($scope[key].qeryOrder != index){
                        $scope[key].header[index].order = false;
                    } else {
                        $scope[key].header[index].order = !$scope[key].header[index].order;
                    }
                    $scope[key].qeryOrder = index;
                } else {
                    if($scope.qeryOrder != index){
                        $scope.header[index].order = false;
                    } else {
                        $scope.header[index].order = !$scope.header[index].order;
                    }
                    $scope.qeryOrder = index;
                }
            };

            $scope.prevPage = function(PageConfig){
                return PageConfig.page = (PageConfig.page-1<0?0:PageConfig.page-1);
            };

            $scope.pageInfo = function(PageConfig){
                return (PageConfig.page +1)+' / '+PageConfig.total_page;
            };

            $scope.nextPage = function(PageConfig){
                return PageConfig.page = (PageConfig.page+1>(PageConfig.total_page-1)?(PageConfig.total_page-1):PageConfig.page+1);
            };

            $scope.triggerGroup = function(item){
                if(item.is_close == true){
                    item.is_close = false;
                } else {
                    item.is_close = true;
                }
            };

            $scope.itemClick = function(item, next, isShowLoading){
                if($scope.select_item)
                    $scope.select_item.isSelect = false;
                item.isSelect = true;
                $scope.select_item = item;
                tabSearch(next, isShowLoading);
            };

            $scope.itemStyle = function(header, item, type){
                if(header.type == 'P'){
                    var _column_setting = detectColumnStyle(header, item);
                    if(type == 'content'){
                        return {'background': _column_setting.bg_color};
                    } else if(type == 'bar'){
                        return {'background':_column_setting.main_color, 'width': _column_setting.persent_value + '%'};
                    } else if(type == 'label'){
                        return {'color':_column_setting.font_color};
                    }
                } else if(header.type == 'L'){
                    var _column_setting = detectColumnStyle(header, item);
                    return {'background':_column_setting.main_color};
                }
                return {};
            }

            $scope.changeView = function(item, chart_info, type){
                if(item == undefined){
                    $('.kmi-chart').css('padding-bottom','0px');
                    $scope.queryMode = 'list';
                } else if(type == 'pie_chart'){
                    $scope.queryMode = 'pie_chart';
                    generatePieChart({
                        data:item.result,
                        item:item,
                        chart_info: chart_info
                    });
                } else {
                    $scope.queryMode = 'chart';
                    generateChart({
                        data:item.result,
                        item:item,
                        chart_info: chart_info
                    });
                }
            };

            $scope.changeTab = function(report_index){
                if(_collection == 'Y'){
                    $scope.select_tab = report_index;
                    //if($scope.tab_result[$scope.select_tab].length == 0)
                    //$scope.beforeSearch({isWarning:true});
                }
                else if($scope.select_item)
                {
                    $scope.select_tab = report_index;
                    //查詢
                    tabSearch();
                } else {
                    $scope.$root.showAlert($filter('translate')('C12.msg.plz_select_item'));
                }
            };

            $scope.setting = function(){
                $mdDialog.serviceDialog('C12Settings',
                angular.extend({}, _refresh),
                function(refresh){
                    _refresh.time = refresh.time;
                    _refresh.page_time = parseInt(refresh.page_time);
                    _refresh.is_start = refresh.is_start;
                    _refresh.font_size = parseInt(refresh.font_size);
                    if($scope.PageConfig){
                        $scope.PageConfig.page_count = _refresh.page_count = parseInt(refresh.page_count);
                    }
                    if($scope.tab_info.length > 0){
                        for(var i = 0; i < $scope.tab_info;i++){
                            $scope['tab_'+i].PageConfig.page_count = _refresh.page_count = parseInt(refresh.page_count);
                        }
                    }

                    //20200331 69092 每張報表都要有自己的localstorage modify by 韋齊
                    localStorage.setItem(config.appName + '_RPT_Settings_'+$scope.$root.currentState, JSON.stringify(_refresh));
                    generateReportStyle();
                    //dog.sleep = _refresh.time;
                    if(!$WatchDogService.isStart && _refresh.is_start == 'Y'){
                        $scope.isClose = true;
                        $WatchDogService.startWatch(dog, true);
                    } else if(_refresh.is_start == 'N'){
                        $WatchDogService.stopWatch();
                    }
                });
            };

            function tabSearch(next, isShowLoading){
                var _conditoin = [],
                    query_condition_info = $scope.tab_info[$scope.select_tab].query_condition_info;//子報表的查詢條件
                if(query_condition_info && query_condition_info.length>0){
                    $scope.beforeSearch({
                        search:function(conditionList){
                            query_condition_info.forEach(function(condition_info){
                                //查詢條件內取出符合子報表使用的查詢條件
                                var _temps = $filter('filter')(conditionList, {column_name:condition_info.query_column}, true);
                                if(_temps.length > 0){
                                    //有對應的查詢條件則優先使用
                                    // 20201228 modify by WeiTing for M#78469 - Excel報表匯出查詢子報表時，只回送後台SQL有加上別名的欄位
                                    if(condition_info.query_column.split('.').length === 1) {
                                        _temps.forEach(function(_temp){
                                            _conditoin.push({
                                                //column_name 轉換成子報表用的欄位
                                                column_name: condition_info.query_condition,
                                                query_mode: _temp.query_mode,
                                                merge_condition_model: _temp.merge_condition_model,
                                                value: _temp.value
                                            });
                                        });
                                    }
                                } else {
                                    //沒有對應的查詢條件則從資料列抓
                                    // 20201201 modify by WeiTing for M#78469 - Excel報表匯出查詢子報表時，只回送後台SQL有加上別名的欄位
                                    if(condition_info.query_column.split('.').length === 1) {
                                        _conditoin.push({
                                            column_name: condition_info.query_condition,
                                            query_mode: condition_info.query_mode||'0',
                                            merge_condition_model: 'AND',
                                            value: $scope.select_item[condition_info.query_column]
                                        });
                                    }
                                }
                            });
                        }
                    });
                }

                userCustomReportDataGet($scope.tab_info[$scope.select_tab].report_id, _conditoin, function(data){
                    $scope.tab_result[$scope.select_tab] = data.report_data;
                    $scope['tab_'+$scope.select_tab].statistics_result = data.report_statistics;
                    if(next)
                        next();
                }, next, isShowLoading == undefined);
            }

            //取得自定義報表格式
            function userCustomReportFormatGet(report_id, callback){
                $MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_SYS.user_custom_report_format_get',
                    content : {report_id:report_id},
                    success : function(data){
                        let url = '';
                        //20210622 modify by Dustdusk for M#93707: C12增加支援外部系統 / 帆軟
                        if(data.reporturl_link && data.reporturl_link.indexOf('http://')==0){
                            let _elem = document.getElementById('report-inner-content');
                            _elem.parentNode.removeChild(_elem);

                            showReport(data.reporturl_link);
                        } else if(data.reporturl_link && $stateParams.data.outside_url && $stateParams.data.outside_url.indexOf('http://')==0){
                            let _elem = document.getElementById('report-inner-content');
                            _elem.parentNode.removeChild(_elem);

                            if (data.reporturl_link.toLowerCase().indexOf('.cpt') > 0) {
                                url = $stateParams.data.outside_url + '/view/report?viewlet=' + data.reporturl_link;
                            } else if (data.reporturl_link.toLowerCase().indexOf('.frm') > 0) {
                                url = $stateParams.data.outside_url + '?formlet=' + data.reporturl_link;
                            }
                            showReport(url);
                        // 20240401 modify by wenwei for M#160928: [6.1beta格尔]自定义看板设定问题
                        } else if (data.reporturl_link && config.cache.sys_parameter.ABI_URL && config.cache.sys_parameter.ABI_URL.indexOf('http://')==0) {
                            let _elem = document.getElementById('report-inner-content');
                            _elem.parentNode.removeChild(_elem);
                            
                            url = config.cache.sys_parameter.ABI_URL + '?' + data.reporturl_link;
                            showReport(url);
                        } else {
                            let _elem = document.getElementById('report-outside-content');
                            _elem.parentNode.removeChild(_elem);

                            _collection = data.collection||'N';
                            $scope.relate_info = data.relate_info;
                            generateCondition(data.query_condition_info);
                            generateReportStyle();
                            $scope.$root.showLoading();
                            // 20230322 modify by Alan for M#130762: 從column_info取得語系加入圖表
                            var chart_info = data.chart_info;
                            if(chart_info && chart_info.setting && chart_info.setting.length > 0) {
                                var xItem = data.column_info.find((item) => item.column_name ===  chart_info.setting[0].xaxis)
                                var yItem = data.column_info.find((item) => item.column_name ===  chart_info.setting[0].yaxis)
                                if(data.column_info && xItem){
                                    chart_info.setting[0].xlabel = xItem.column_display;
                                }
                                if(data.column_info && yItem){
                                    chart_info.setting[0].ylabel = yItem.column_display;
                                }
                            }
                            generateGroup({
                                target:$('#report_content'),
                                bind:'result',
                                collection: _collection,
                                group_info:data.group_info,//群組資訊
                                column_info:data.column_info,//欄位資訊
                                statistics_info:data.statistics_info,//統計資訊(小計/總計)
                                chart_info: chart_info,//圖表資訊
                                isRelate:(data.relate_info&&data.relate_info.length>0)
                            }, function(){
                                _relate_info = data.relate_info;
                                generateTab({
                                    target:$('#report_content'),
                                    relate_info:data.relate_info//單身資訊
                                }, function(){
                                    $timeout(function(){
                                        $compile(document.getElementById('report_content'))($scope);
                                        $timeout(function(){
                                            $('#report_content').css('opacity', 1);
                                            $scope.$root.hideLoading();
                                            if(callback)
                                                callback(data);
                                        });
                                    });
                                });
                            });
                        }
                    },
                    error:function(data){
                        $scope.$root.showAlert(data.Message);
                        $scope.$root.changeProgram('home', true);
                    }
                });
            }

            function userCustomReportDataGet(report_id, condition, callback, next, isShowLoading){
                $MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_SYS.user_custom_report_data_get',
                    content : {
                        report_id:report_id,
                        query_condition_info:condition
                    },
                    success : function(data){
                        if(callback){
                            callback(data);
                        } else {
                            $scope.result = data.report_data;
                            $scope.statistics_result = data.report_statistics;
                            // 20190809 modify by WeiTing for M#60871: 拿掉 ng-disabled 的判斷式，調整成匯出不必先查詢，就能直接按匯出。
                            $scope.queryMode = 'list';
                            if($scope.tab_info && $scope.tab_info.length>0){
                                if($scope.result && $scope.result.length>0){
                                    // 20200728 modify by WeiTing for M#74924 - 修正子母報表不能有自動更新功能，只有單個報表才能使用自動更新功能。
                                    if($scope.result[0].result && $scope.result[0].result.length>0){
                                        $scope.itemClick($scope.result[0].result[0]);
                                    } else {
                                        $scope.itemClick($scope.result[0]);
                                    }
                                    // 20200728 modify by WeiTing for M#74924 - 修正子母報表不能有自動更新功能，只有單個報表才能使用自動更新功能。
                                    // if(next && $scope.select_item){
                                    //     //有[挑選]並且[自動更新]，則沿用已選的該筆
                                    //     $scope.itemClick($scope.select_item, next, isShowLoading);
                                    // } else if($scope.result[0].result && $scope.result[0].result.length>0){
                                    //     $scope.itemClick($scope.result[0].result[0], next, isShowLoading);
                                    // } else {
                                    //     $scope.itemClick($scope.result[0], next, isShowLoading);
                                    // }
                                } else {
                                    $scope.tab_result[$scope.select_tab] = [];
                                    $scope.select_item = undefined;
                                    // 20200728 modify by WeiTing for M#74924 - 修正子母報表不能有自動更新功能，只有單個報表才能使用自動更新功能。
                                    // if(next)
                                    //     next();
                                }
                            } else {
                                if(next)
                                    next();
                            }
                        }
                    }
                }, isShowLoading);
            }

            function exportExcel(report_id, condition, callback){
                if(window.nodeRequire){
                    //20210111 add by linzh for M#70346:获取暂存的用户自定义栏位顺序 --------------------start---------------
                    var content = {
                        report_id: report_id,
                        query_condition_info: condition
                    };
                    //单头栏位
                    var headerColumnListStr = localStorage.getItem('C12_' + $scope.$root.currentState + '_list');
                    var headerColumnList = JSON.parse(headerColumnListStr);
                    if (headerColumnList != null) {
                        content.header_column_list = headerColumnList;
                    }
                    //单身栏位
                    if ($scope.tab_info.length > 0) {
                        var relateHeaderColumnList = [];
                        for (var i = 0; i < $scope.tab_info.length; i++) {
                            var relateHeaderColumnListStr = localStorage.getItem('C12_' + $scope.$root.currentState + '_tab_' + i + '.list');
                            if (relateHeaderColumnListStr != null)
                                relateHeaderColumnList.push(JSON.parse(relateHeaderColumnListStr))
                            else
                                relateHeaderColumnList.push(null);
                        }
                        content.relate_header_column_list = relateHeaderColumnList;
                    }
                    //20210111 add by linzh for M#70346:获取暂存的用户自定义栏位顺序 --------------------end---------------
                    try {
                        // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
                        const { remote } = window.nodeRequire('electron');
                        if (remote) {
                            remote.dialog.showOpenDialog({
                                properties: ['openDirectory']
                            }, function (fileList) {
                                if (fileList && fileList.length > 0) {
                                    $rootScope.showToast($filter('translate')('common.msg.file_downloading'));
                                    $MMWService.sendToServer({
                                        uri: 'ServicesSTD.Module_SYS.user_custom_report_excel_get',
                                        content: content,
                                        success: function (data) {
                                            if (callback) {
                                                callback(data);
                                            } else {
                                                var file_data = Buffer.from(data.file_data, 'base64');
                                                var file_title = $scope.title.replace(new RegExp("\/", "gm"), "-");
                                                //20220810 modify by 王晴晴 for M#0115351 将excel汇出的档案格式更改为xlsx
                                                var file_name = fileList[0] + '\\' + file_title + moment().format('YYYYMMDDHHmmss') + '.xlsx';
                                                window.nodeRequire('fs').writeFile(file_name, file_data, function (error) {
                                                    if (error) {
                                                        $rootScope.showAlert($filter('translate')('common.msg.cantDownloadFile') + error);
                                                    } else {
                                                        $mdlToast.hide();
                                                        $rootScope.showConfirm($filter('translate')('common.msg.file_download_complete_and_open'), function (dialog) {
                                                            dialog.hide();
                                                            try {
                                                                window.nodeRequire('electron').shell.openItem(file_name);
                                                            } catch (error) {
                                                                nw.Shell.openItem(file_name);
                                                            }
                                                        });
                                                    }
                                                });
                                            }
                                        }
                                    }, false);
                                }
                            });
                        } else {
                            const remote = window.nodeRequire('@electron/remote');
                            remote.dialog.showOpenDialog({
                                properties: ['openDirectory']
                            }).then((result) => {
                                if (result.filePaths && result.filePaths.length > 0) {
                                    $rootScope.showToast($filter('translate')('common.msg.file_downloading'));
                                    $MMWService.sendToServer({
                                        uri: 'ServicesSTD.Module_SYS.user_custom_report_excel_get',
                                        content: content,
                                        success: function (data) {
                                            if (callback) {
                                                callback(data);
                                            } else {
                                                var file_data = Buffer.from(data.file_data, 'base64');
                                                var file_title = $scope.title.replace(new RegExp("\/", "gm"), "-");
                                                //20220810 modify by 王晴晴 for M#0115351 将excel汇出的档案格式更改为xlsx
                                                var file_name = result.filePaths[0] + '\\' + file_title + moment().format('YYYYMMDDHHmmss') + '.xlsx';
                                                window.nodeRequire('fs').writeFile(file_name, file_data, function (error) {
                                                    if (error) {
                                                        $rootScope.showAlert($filter('translate')('common.msg.cantDownloadFile') + error);
                                                    } else {
                                                        $mdlToast.hide();
                                                        $rootScope.showConfirm($filter('translate')('common.msg.file_download_complete_and_open'), function (dialog) {
                                                            dialog.hide();
                                                            try {
                                                                window.nodeRequire('electron').shell.openPath(file_name);
                                                            } catch (error) {
                                                                nw.Shell.openItem(file_name);
                                                            }
                                                        });
                                                    }
                                                });
                                            }
                                        }
                                    }, false);
                                }
                            });
                        }
                    } catch (error) {

                        $rootScope.showToast($filter('translate')('common.msg.file_downloading'));
                        $MMWService.sendToServer({
                            uri : 'ServicesSTD.Module_SYS.user_custom_report_excel_get',
                            content: content,
                            success : function(data){
                                if(callback){
                                    callback(data);
                                } else {
                                    var fs = window.nodeRequire('fs');

                                    var filePath = window.nodeRequire('path').dirname(process.execPath)+'\\Custom_Report_Excel\\';
                                    var file_data = Buffer.from(data.file_data, 'base64');

                                    if(!fs.existsSync(filePath)){
                                        fs.mkdirSync(filePath);
                                    }
                                    //20220810 modify by 王晴晴 for M#0115351 将excel汇出的档案格式更改为xlsx
                                    var file_name = filePath+$scope.title+moment().format('YYYYMMDDHHmmss')+'.xlsx';
                                    fs.writeFile(file_name, file_data, function(error){
                                        if(error){
                                            $rootScope.showAlert($filter('translate')('common.msg.cantDownloadFile')+error);
                                        } else {
                                            $mdlToast.hide();
                                            $rootScope.showConfirm($filter('translate')('common.msg.file_download_complete_and_open'), function(dialog){
                                                dialog.hide();
                                                nw.Shell.openItem(file_name);
                                            });
                                        }
                                    });
                                }
                            }
                        }, false);


                    }

                } else {
                    $rootScope.showToast($filter('translate')('common.msg.file_download_complete'));
                }


            }

            //組合conditoin
            // 20220223 modify by Alan for M#103705: 新增filedType == 2 ('D')時的預設值
            function generateCondition(condition_info){
                var filedType = {'2':'D', '3':'D', '4':'N', '5':'C', '6':'SE'};
                if(condition_info && condition_info.length>0){
                    var temp_codeList = [];
                    condition_info.forEach(function(condition, index){
                        var _columnItem = {
                            order:index,
                            name:condition.column_display,
                            column_name:condition.column_name,
                            datasource_format_info:condition.datasource_format_info,
                            require:condition.require,
                            condoperand:condition.condoperand,
                            default_value:condition.default_value,
                            query_mode: condition.condoperand
                        };
                        if(condition.datasource_format_info !== null)
                            _columnItem.data_type = 'S';
                        else
                            _columnItem.data_type = filedType[condition.field_type];

                        if ( _columnItem.data_type === 'D') {
                            var defaultDay = getDate(_columnItem.default_value);
                            _columnItem.default_value = defaultDay;
                            _columnItem.value = defaultDay;
                            condition.default_value = defaultDay;
                        }
                        temp_codeList.push(_columnItem);
                    });
                    $scope.codeList = temp_codeList;
                } else {
                    $scope.codeList = [];
                }
            }

            function getDate(value) {
                var parsedValue = Number(value);
                if (parsedValue > 0) {
                    return moment().add(parsedValue, 'days').format('YYYY/MM/DD');
                } else if (parsedValue < 0) {
                    return moment().subtract(-(parsedValue), 'days').format('YYYY/MM/DD');
                } else {
                    return moment().format('YYYY/MM/DD');
                }
            }
            
            function generateTab(options, callback){
                if(options.relate_info && options.relate_info.length>0){
                    $scope.select_tab = 0;
                    var tapContent = $('<div class="tap-contenter perfect-scrollbar"></div>').appendTo(options.target);
                    options.relate_info.forEach(function(relate_info, index){
                        tapContent.append('<div class="tab" ng-class="{\'is-select\':select_tab == \''+index+'\'}" ng-click="changeTab(\''+index+'\');">'+relate_info.report_desc+'<div class="kmi-can-click"></div></div>');
                        $scope.tab_result[index] = [];
                        $scope.tab_info[index] = {report_id:relate_info.report_id, query_condition_info:relate_info.query_condition_info};
                        generateGroup({
                            target:$('<div class="tab-content" ng-show="select_tab == \''+index+'\'"></div>').appendTo(options.target),
                            bind:'tab_result[\''+index+'\']',
                            id:'tab_'+index,
                            group_info:relate_info.group_info,
                            column_info:relate_info.column_info,
                            statistics_info:relate_info.statistics_info,
                            chart_info:relate_info.chart_info,//圖表資訊
                        });
                    });
                }
                if(callback)
                    callback();
            }

            //動態組合kmi-group-list
            function generateGroup(options, callback){
                if (options.collection == 'Y'){
                    if(callback)
                        callback();
                } else if(options.group_info && options.group_info.length>0){
                    var report_content = '<div class="kmi-list column-selector"></div>',
                        total_width = 0,
                        group_id = '',
                        page_id = '',
                        header,
                        row_content,
                        group_row,
                        row;
                    if(options.id != undefined){
                        group_id += options.id+'.';
                        page_id = options.id+'[$index].';
                        $scope[options.bind] = [];
                        $scope[options.id] = {};
                        $scope[options.id].header = [];
                        $scope[options.id].filterColumns = {};
                        $scope[options.id].statistics_result = {};
                        $scope[options.id].chart_info = options.chart_info;
                    } else {
                        page_id = 'main[$index].';
                        $scope.result = [];
                        $scope.header = [];
                        $scope.filterColumns = {};
                        $scope.statistics_result = {};
                        $scope.chart_info = options.chart_info;
                    }

                    options.target.attr('ng-init', group_id+'PageConfig = {page_count : '+_refresh.page_count+'}');

                    if(options.chart_info != null){

                        var tab = '<div class="kmi-chart-title-bar">'
                                +     '<div class="kmi-button kmi-button-confirm"style="width:100px;position: absolute;top:0px;right: 2px;">'
                                +         '<label ng-bind="\'common.btn.close\' | translate"></label>'
                                +         '<div class="kmi-can-click"  ng-click="changeView();" ></div>'
                                +     '</div>'
                                +     '<div class="chart-title" ng-bind="chart_title"></div>'
                                +     '</div>';
                        $(tab).appendTo(options.target);
                    }
                    report_content = $(report_content).appendTo(options.target)
                    report_content.attr('column-selector-id', $stateParams.data.report_id+'_'+group_id+'list');
                    header = $('<div class="kmi-list__header"></div>').appendTo(report_content);
                    row_content = $('<div class="kmi-list__row-content" id="'+ group_id.replace('.', '_') + 'result_list"></div>').appendTo(report_content);

                    //群列
                    group_row = $('<div class="kmi-list__row start"></div>').appendTo(row_content)
                        .attr('ng-repeat-start','group_item in getGroupPages('+options.bind+', '+group_id+'PageConfig, '+group_id+'filterColumns, ' + group_id+'header['+group_id+'qeryOrder]) track by $index')
                        .attr('ng-class','{\'hidden-details\':group_item.is_close}');
                        //.attr('ng-init', page_id+'PageConfig = {page_count : '+page_count+'}');//初始化群分頁
                    options.group_info.forEach(function(info, i){
                        if(i==0){
                            group_row.append('<div class="close-btn" ng-click="triggerGroup(group_item);">'
                                + '<i class="material-icons close">remove</i>'
                                + '<i class="material-icons open">add</i>'
                                + '<div class="kmi-can-click"></div>'
                                + '</div>');
                            if(options.chart_info && options.chart_info.setting){
                                var pie_chart = $filter('filter')(options.chart_info.setting, {type:'pie'});
                                if(options.chart_info.setting.length > pie_chart.length){
                                    group_row.append('<div class="chart-btn" ng-click="changeView(group_item, '+group_id+'chart_info);">'
                                    + '<i class="material-icons close">assessment</i>'
                                    + '<div class="kmi-can-click"></div>'
                                    + '</div>');
                                }
                                //20190213 add by Dustdusk for M#: 增加群組圖表功能
                                if(pie_chart && pie_chart.length >0){
                                    group_row.append('<div class="chart-btn" ng-click="changeView(group_item, '+group_id+'chart_info, \'pie_chart\');">'
                                    + '<i class="material-icons close">pie_chart</i>'
                                    + '<div class="kmi-can-click"></div>'
                                    + '</div>');
                                }
                            }
                        }
                        var column_html = '<div class="group__column">'
                            + '<label class="title_style">'+info.column_display+'：</label>'
                            + '{{group_item[\''+ info.column_name +'\']}}'
                            + '</div>';
                        group_row.append(column_html);
                    });
                    group_row.append('<div class="group__Horizontal"></div>');

                    //一般列
                    row = $('<div class="kmi-list__row"></div>').appendTo(row_content)
                        //.attr('ng-repeat','item in getPages(group_item.result, '+page_id+'PageConfig, '+group_id+'filterColumns) track by $index')
                        //.attr('ng-repeat','item in group_item.result | filter:'+group_id+'filterColumns track by $index')
                        .attr('ng-repeat','item in getGroupResult(group_item, '+group_id+'filterColumns, '+group_id+'header['+group_id+'qeryOrder]) track by $index')
                        //.attr('ng-class','{\'is-select\':item.isSelect, \'hidden-details\':group_item.is_close}');
                        .attr('ng-class','{\'is-select\':item.isSelect}');

                    header.append('<div class="kmi-list__column width-fixed" style="flex:0 0 28px;"></div>');
                    row.append('<div class="kmi-list__column width-fixed" style="flex:0 0 28px;"></div>');
                    options.column_info.forEach(function(condition, i){
                        //20190212 modify by Dustdusk for M#: 增加可以隱藏報表欄位
                        if(condition.column_name.indexOf('_') != 0){
                            // 欄位標題
                            var headerColumn = '<div class="kmi-list__column head-controls" style="flex:1;">';
                            headerColumn += '<div class="filter" ng-show="'+group_id+'header['+i+'].isFilter">';
                            headerColumn += '<input ng-model="'+group_id+'filterColumns[\''+condition.column_name + '\']"/>';
                            headerColumn += '<i class="material-icons clear" style="position: absolute;top: 2px;right: 4px;" ng-click="'+group_id+'header['+i+'].isFilter = false;'+group_id+'filterColumns[\''+ condition.column_name +'\'] = \'\';">clear</i>';
                            headerColumn += '</div>';
                            headerColumn += '<div class="order" ng-hide="'+group_id+'header['+i+'].isFilter">';
                            headerColumn += '<i class="material-icons search" style="z-index:1;" ng-click="'+group_id+'header['+i+'].isFilter = true">search</i>';
                            headerColumn += '<label>'+condition.column_display+'</label>';
                            headerColumn += '<i class="material-icons" ng-show="'+group_id+'qeryOrder == '+i+'">{{!'+group_id+'header['+i+'].order?\'&#xE5D8;\':\'&#xE5DB;\'}}</i>';
                            //headerColumn += '<div class="kmi-can-click" ng-click="orderResult('+i+', '+group_id+'header['+i+']);"></div>';
                            if(options.id != undefined){
                                headerColumn += '<div class="kmi-can-click" ng-click="orderResult('+i+', \''+ options.id +'\');"></div>';
                            } else {
                                headerColumn += '<div class="kmi-can-click" ng-click="orderResult('+i+');"></div>';
                            }
                            headerColumn += '</div>';
                            headerColumn += '</div>';
                            header.append(headerColumn);
                            // 欄位內容
                            var listColumn = '<div class="kmi-list__column" style="flex:1;z-index:0;"';
                                listColumn += 'ng-class="{\' column-border\':!$last}"';
                            if(condition.column_type == 'L'){
                                listColumn += '><div class="item-light" ng-style="itemStyle(header['+i+'], item);"/>';
                            } else if(condition.column_type == 'P'){
                                listColumn += '>'
                                listColumn += '<div class="item-bar-content" ng-style="itemStyle(header['+i+'], item, \'content\');">';
                                listColumn += '<div class="item-bar" ng-style="itemStyle(header['+i+'], item, \'bar\');"></div>';
                                listColumn += '<div class="item-bar-label" ng-style="itemStyle(header['+i+'], item, \'label\');" ng-bind="item[\''+ condition.column_name +'\']" ></div>';
                                listColumn += '</div>';
                            } else {
                                listColumn += ' ng-bind="item[\''+ condition.column_name +'\']" >';
                            }
                            listColumn += '</div>';
                            row.append(listColumn);

                            var _header_info = {
                                code:condition.column_name,
                                type:condition.column_type,
                                setting:condition.column_setting
                            };
                            if(options.id != undefined){
                                $scope[options.id].header[i] = _header_info;
                            } else {
                                $scope.header[i] = _header_info;
                            }
                            total_width += 120;//先暫定每個欄位寬度120px;
                        }
                    });
                    report_content.attr('kmi-scrollbar',total_width+'px');
                    if(options.isRelate){
                        row.append('<div class="kmi-can-click" ng-click="itemClick(item);"></div>');
                    }
                    //群小計
                    if(options.statistics_info && options.statistics_info.length > 0){
                        var group_total_row = $('<div class="kmi-list__row end total-content"></div>').appendTo(row_content);
                        options.statistics_info.forEach(function(statistics){
                            group_total_row.append('<label class="total-name">'+statistics.column_display+'：</label><label class="total-value" ng-bind="group_item[\''+ statistics.column_name +'\']"></label>');
                        });
                    }
                    row_content.append('<span ng-repeat-end></span>');

                    //總計
                    if(options.statistics_info && options.statistics_info.length > 0){
                        var totalContent = $('<div class="total-content"></div>').appendTo(options.target);
                        options.statistics_info.forEach(function(total){
                            if(options.id != undefined){
                                $scope[options.id].statistics_result[total.column_name] = 0;
                            } else {
                                $scope.statistics_result[total.column_name] = 0;
                            }
                            totalContent.append('<label class="total-name">'+total.column_display+'：</label><label class="total-value" ng-bind="'+group_id+'statistics_result[\''+total.column_name+'\']"></label>');
                        });
                    }

                    //20191030 modify by Dustdusk for M#: 增加圖表
                    if(options.chart_info != null){
                        generateChartTemplate(options);
                    }

                    $('<div class="page-content"></div>').appendTo(options.target)
                        .append('<div class="page-icon"><img src="image/icons/dropleft.png"></img><div class="kmi-can-click"  ng-click="prevPage('+group_id+'PageConfig);"></div></div>')
                        .append('<label ng-bind="pageInfo('+group_id+'PageConfig);"></label>')
                        .append('<div class="page-icon"><img src="image/icons/dropright.png"></img><div class="kmi-can-click"  ng-click="nextPage('+group_id+'PageConfig);"></div></div>');

                    if(callback){
                        callback();
                    }
                } else {
                    generateResults({
                        target:options.target,
                        id:options.id,
                        bind:options.bind,
                        column_info:options.column_info,
                        statistics_info:options.statistics_info,
                        chart_info:options.chart_info,
                        isRelate:options.isRelate
                    }, function(){
                        if(callback)
                            callback();
                    });
                }
            }

            //動態組合kmi-list
            function generateResults(options, callback){
                if(options.column_info && options.column_info.length>0){
                    var report_content = '<div class="kmi-list column-selector"></div>',
                        total_width = 0,
                        result_id = '',
                        tab,
                        header,
                        row;
                    if(options.id != undefined){
                        result_id += options.id+'.';
                        $scope[options.id] = {};
                        $scope[options.id][options.bind] = [];
                        $scope[options.id].header = [];
                        $scope[options.id].filterColumns = {};
                        $scope[options.id].statistics_result = {};
                        $scope[options.id].chart_info = {};
                    } else {
                        $scope.result = [];
                        $scope.header = [];
                        $scope.filterColumns = {};
                        $scope.statistics_result = {};
                        $scope.chart_info = options.chart_info;
                    }

                    options.target.attr('ng-init', result_id+'PageConfig = {page_count : '+_refresh.page_count+'}');

                    if(options.chart_info != null && options.chart_info.setting){
                        var tab = '<div class="switch-content">'
                            //+     '<label class="label" ng-bind="\'C00.view_mode\' | translate"></label>'
                            +     '<div class="kmi-button switch-button" ng-click="changeView();" style="width:100px" ng-class="{\'is-selected\':queryMode == \'list\'}">'
                            +         '<label ng-bind="\'common.btn.table\' | translate"></label>'
                            +         '<div class="kmi-can-click"></div>'
                            +     '</div>';
                            var pie_chart = $filter('filter')(options.chart_info.setting, {type:'pie'});
                            if(options.chart_info.setting.length > pie_chart.length){
                                tab +='<div class="kmi-button switch-button" ng-click="changeView({result:'+options.bind+'}, '+result_id+'chart_info);"  ng-class="{\'is-selected\':queryMode == \'chart\'}">'
                                    +     '<label ng-bind="\'common.btn.chart\' | translate"></label>'
                                    +     '<div class="kmi-can-click"></div>'
                                    + '</div>';
                            }
                            if(pie_chart && pie_chart.length>0) {
                                tab += '<div class="kmi-button switch-button" ng-click="changeView({result:'+options.bind+'}, '+result_id+'chart_info, \'pie_chart\');"  ng-class="{\'is-selected\':queryMode == \'pie_chart\'}">'
                                    +      '<label ng-bind="\'common.btn.pie_chart\' | translate"></label>'
                                    +      '<div class="kmi-can-click"></div>'
                                    +  '</div>';
                            }
                            tab     += '</div>';
                        $(tab).appendTo(options.target);
                    }

                    report_content = $(report_content).appendTo(options.target);
                    report_content.attr('column-selector-id', $stateParams.data.report_id+'_'+result_id+'list');
                    header = $('<div class="kmi-list__header"></div>').appendTo(report_content);
                    row = $('<div class="kmi-list__row"></div>').appendTo($('<div class="kmi-list__row-content" id="'+ result_id.replace('.', '_') + 'result_list"></div>').appendTo(report_content))
                        .attr('ng-repeat','item in getPages('+options.bind+', '+result_id+'PageConfig, '+result_id+'filterColumns, '+result_id+'header['+result_id+'qeryOrder]) track by $index')
                        .attr('ng-class','{\'is-select\':item.isSelect}');

                    options.column_info.forEach(function(condition, i){
                        //20190212 modify by Dustdusk for M#: 增加可以隱藏報表欄位
                        if(condition.column_name.indexOf('_') != 0){
                            // 欄位標題
                            var headerColumn = '<div class="kmi-list__column head-controls" style="flex:1;">';
                            headerColumn += '<div class="filter" ng-show="'+result_id+'header['+i+'].isFilter">';
                            headerColumn += '<input ng-model="'+result_id+'filterColumns[\''+condition.column_name + '\']"/>';
                            headerColumn += '<i class="material-icons clear" style="position: absolute;top: 2px;right: 4px;" ng-click="'+result_id+'header['+i+'].isFilter = false;'+result_id+'filterColumns[\''+ condition.column_name +'\'] = \'\';">clear</i>';
                            headerColumn += '</div>';
                            headerColumn += '<div class="order" ng-hide="'+result_id+'header['+i+'].isFilter">';
                            headerColumn += '<i class="material-icons search" style="z-index:1;" ng-click="'+result_id+'header['+i+'].isFilter = true">search</i>';
                            headerColumn += '<label>'+condition.column_display+'</label>';
                            headerColumn += '<i class="material-icons" ng-show="'+result_id+'qeryOrder == '+i+'">{{!'+result_id+'header['+i+'].order?\'&#xE5D8;\':\'&#xE5DB;\'}}</i>';
                            if(options.id != undefined){
                                headerColumn += '<div class="kmi-can-click" ng-click="orderResult('+i+', \''+ options.id +'\');"></div>';
                            } else {
                                headerColumn += '<div class="kmi-can-click" ng-click="orderResult('+i+');"></div>';
                            }
                            headerColumn += '</div>';
                            headerColumn += '</div>';
                            header.append(headerColumn);

                            // 欄位內容
                            var listColumn = '<div class="kmi-list__column" style="flex:1;z-index:0;"';
                                listColumn += 'ng-class="{\' column-border\':!$last}"';
                            if(condition.column_type == 'L'){
                                listColumn += '><div class="item-light" ng-style="itemStyle(header['+i+'], item);"/>';
                            } else if(condition.column_type == 'P'){
                                listColumn += '>'
                                listColumn += '<div class="item-bar-content" ng-style="itemStyle(header['+i+'], item, \'content\');">';
                                listColumn += '<div class="item-bar" ng-style="itemStyle(header['+i+'], item, \'bar\');"></div>';
                                listColumn += '<div class="item-bar-label" ng-style="itemStyle(header['+i+'], item, \'label\');" ng-bind="item[\''+ condition.column_name +'\']" ></div>';
                                listColumn += '</div>';
                            } else {
                                listColumn += ' ng-bind="item[\''+ condition.column_name +'\']" >';
                            }
                            listColumn += '</div>';
                            row.append(listColumn);

                            //ColumnInfo
                            var _header_info = {
                                code:condition.column_name,
                                type:condition.column_type,
                                setting:condition.column_setting
                            };
                            if(options.id != undefined){
                                $scope[options.id].header[i] = _header_info;
                            } else {
                                $scope.header[i] = _header_info;
                            }
                            total_width += 120;//先暫定每個欄位寬度120px;
                        }
                    });
                    report_content.attr('kmi-scrollbar',total_width+'px');
                    if(options.isRelate){
                        row.append('<div class="kmi-can-click" ng-click="itemClick(item);"></div>');
                    }

                    //總計
                    if(options.statistics_info && options.statistics_info.length > 0){
                        var totalContent = $('<div class="total-content"></div>').appendTo(options.target);
                        options.statistics_info.forEach(function(total){
                            if(options.id != undefined){
                                $scope[options.id].statistics_result[total.column_name] = 0;
                            } else {
                                $scope.statistics_result[total.column_name] = 0;
                            }
                            totalContent.append('<label class="total-name">'+total.column_display+'：</label><label class="total-value" ng-bind="'+result_id+'statistics_result[\''+total.column_name+'\']"></label>');
                        });
                    }

                    $('<div class="page-content"></div>').appendTo(options.target)
                        .append('<div class="page-icon"><img src="image/icons/dropleft.png"></img><div class="kmi-can-click"  ng-click="prevPage('+result_id+'PageConfig);"></div></div>')
                        .append('<label ng-bind="pageInfo('+result_id+'PageConfig);"></label>')
                        .append('<div class="page-icon"><img src="image/icons/dropright.png"></img><div class="kmi-can-click"  ng-click="nextPage('+result_id+'PageConfig);"></div></div>');

                    //20191030 modify by Dustdusk for M#: 增加圖表
                    if(options.chart_info != null){
                        generateChartTemplate(options);
                    }
                    if(callback){
                        callback(report_content);
                    }
                }
            }

            function generateChartTemplate(options){
                var _content = '<div class="kmi-chart">'
                             +     '<div class="kmi-chart-content">'
                             +     '<div id="kmi-chart"></div>'
                             +     '</div>'
                             + '</div>';
                $(_content).appendTo(options.target);
            }

            // 20230322 modify by Alan for M#130762: 調整外觀
            //產生Chart 圖
            function generateChart(options){
                clearChart();
                $('.kmi-chart').css('padding-bottom','8px');
                $timeout(function(){
                    var seriesData = [], seriesColors = [], series = [], xaxisTicks = {}, max = 0,
                        defaultLines = {
                            disableStack:true,
                            pointLabels: {show: true, formatString: '%d%', location:'n'}
                        },
                        defaultBar = {
                            pointLabels:{show:true, location:'s'},
                            renderer:$.jqplot.BarRenderer,
                            rendererOptions: { shadowOffset: 1, barPadding:0, barWidth: 25, highlightMouseDown:true}
                        };
                    $scope.chart_title = $filter('translate')(options.chart_info.title, options.item);
                    //var pie_settings = $filter('filter')(options.chart_info.setting, {type:'!pie'});
                    options.chart_info.setting.forEach(function(setting, i){
                        if(setting.type=='pie')
                            return;

                        var j = 0;
                        options.data.forEach(function(detail){
                            if(seriesData[i] == undefined)
                                seriesData[i] = [];

                            if(xaxisTicks[detail[setting.xaxis]] == undefined)
                                xaxisTicks[detail[setting.xaxis]] = [];

                            var value = detail[setting.yaxis];
                            if(value && !isNaN(value)){
                                value = parseFloat(value);
                            } else {
                                value = 0;
                            }
                            //seriesData[i].push([detail[setting.xaxis], value]);
                            if(xaxisTicks[detail[setting.xaxis]][i] == undefined){
                                xaxisTicks[detail[setting.xaxis]][i] = j;
                                seriesData[i][j] = value;
                                j++;
                            } else {
                                var _j = xaxisTicks[detail[setting.xaxis]][i];
                                seriesData[i][_j] += value;
                            }
                        });

                        var chatSetting = {};
                        if(setting.type == 'line'){
                            chatSetting = angular.extend(chatSetting, defaultLines);
                        } else if(setting.type == 'bar'){
                            chatSetting = angular.extend(chatSetting, defaultBar);
                            //chatSetting.disableStack = !setting.stack_series;
                        }
                        chatSetting.label = setting.label;
                        series.push(chatSetting);
                        // 20230320 modify by Alan for M#130762: 預設黑色，避免後端沒會傳時報錯
                        seriesColors.push(setting.color || '#000000');
                    });

                    var _array_xaxisTicks = Object.keys(xaxisTicks);
                    //$('#kmi-chart').css('min-width', '100%').css('width', (options.data.length*85)+'px');
                    $('#kmi-chart').css('min-width', '100%').css('width', (_array_xaxisTicks.length*85)+'px').css('height', '100%');
                    // 20230320 modify by Alan for M#130762: 新增標題
                    var plot = $.jqplot('kmi-chart', seriesData, {
                        title: {
                            text: $scope.chart_title,
                            fontSize: '1.5em',
                            fontWeight: 700,
                            rendererOptions: { padding: 8}
                        },
                        stackSeries:options.chart_info.stack_series=='Y',
                        series:series,
                        //顏色
                        seriesColors:seriesColors,
                        axesDefaults: { tickRenderer: $.jqplot.CanvasAxisTickRenderer},
                        axes: {
                            //X軸
                            xaxis: {
                                renderer: $.jqplot.CategoryAxisRenderer,
                                ticks:_array_xaxisTicks,
                                label: options.chart_info.setting[0].xlabel
                            }
                            //Y軸
                            , yaxis: {
                                min:0, autoscale:true,
                                tickOptions:{ formatString: '%d', fontSize:'14px' },
                                label: options.chart_info.setting[0].ylabel
                            }
                        },
                        grid: {
                            backgroundColor: '#ffffff',
                            drawBorder:false,
                            shadow:false
                        },
                        //標籤
                        legend:{
                            renderer: $.jqplot.EnhancedLegendRenderer,
                            show:true,
                            placement: 'outsideGrid',
                            rendererOptions: { numberRows: 1, },
                            location:'e',
                            fontSize:'16px',
                        }
                    });

                    $(window).resize(function() {
                        if(plot) {
                            plot.replot( { resetAxes: true } );
                        }
                    });

                    // 20191030 click events
                    $('#kmi-chart').bind('jqplotDataClick',
                        function (ev, seriesIndex, pointIndex, data) {
                            //取出X軸欄位
                            var _temp = {};
                            _temp[options.chart_info.setting[seriesIndex].xaxis] = _array_xaxisTicks[pointIndex];
                            var _select_item = $filter('filter')(options.data, _temp, true);
                            $scope.itemClick(_select_item[0]);
                        }
                    );
                },100);
            }

            //產生Chart 圖
            function generatePieChart(options){
                clearChart();
                $('.kmi-chart').css('padding-bottom','8px');
                var seriesData = {}, labelData=[], _max_value = 0;
                var pie_settings = $filter('filter')(options.chart_info.setting, {type:'pie'});
                pie_settings.forEach(function(setting, i){
                    $scope.chart_title = $filter('translate')(options.chart_info.title, options.item) + '-'+ setting.label;
                    var j = 0;
                    options.data.forEach(function(detail){
                        var _tag = detail[setting.xaxis];
                        if(seriesData[_tag] == undefined)
                            seriesData[_tag] = [_tag, 0];

                        var value = detail[setting.yaxis];
                        if(value && !isNaN(value)){
                            value = parseFloat(value);
                        } else {
                            value = 0;
                        }
                        seriesData[_tag][1] += value;
                        _max_value += value;
                        //labelData.push();
                        //seriesData.push([detail[setting.xaxis], value]);
                    });
                });
                var _datas = $rootScope.getValueforObj(seriesData);
                _datas.forEach(function(_data){
                    labelData.push(_data[0] + ' (' + Math.round(_data[1]/_max_value * 100) + '%)');
                });
                $timeout(function(){
                    $.jqplot('kmi-chart', [_datas], {
                        grid: {
                            drawBorder: false,
                            drawGridlines: false,
                            background: '#ffffff',
                            shadow:false
                        },
                        axesDefaults: {

                        },
                        seriesDefaults:{
                            renderer:$.jqplot.PieRenderer,
                            rendererOptions: {
                                sliceMargin: 2,
                                showDataLabels: false
                            }
                        },
                        //標籤
                        legend:{
                            renderer: $.jqplot.EnhancedLegendRenderer,
                            show:true,
                            /*placement: 'outside',*/
                            /*rendererOptions: { numberRows: 1, },*/
                            location:'e',
                            fontSize:'20px',
                            labels:labelData
                        }
                    });
                    var legend = $('table.jqplot-table-legend');
                    var _html = legend.css('top', '0px').css('left', '0px').css('border', '0px').get(0).outerHTML;
                    $('table.jqplot-table-legend').replaceWith('<div class="jqplot-table-legend-div">' + _html + '</div>');
                });
            }

            function clearChart(){
                $('table.jqplot-table-legend').remove();
                $('#kmi-chart').html('');
                $('#kmi-chart').unbind();
            }

            function detectColumnStyle(header, item){
                if(item[header.code+'_style'] == undefined){
                    if(header.setting){
                        if(item[header.code] != undefined && item[header.code] !== null){
                            for(var i=0;i<header.setting.length;i++){
                                var _setting = header.setting[i];
                                // 20240229 modify by wenwei for M#154017: [MSSQL][H5][自定义报表]配置栏位显示配置后H5不显示此栏位[60090环境可复现]
                                if(_setting.ConditionType == 0){
                                    //等於 =
                                    if(item[header.code] == _setting.ConditionValue){
                                        item[header.code+'_style'] = {
                                            main_color:_setting.MainColor,
                                            bg_color:_setting.BGColor,
                                            font_color:_setting.FontColor,
                                            persent_value: isNaN(item[header.code])?0:item[header.code]
                                        };
                                    }
                                } else if(_setting.ConditionType == 1){
                                    // 不等於 !=
                                    if(item[header.code] != _setting.ConditionValue){
                                        item[header.code+'_style'] = {
                                            main_color:_setting.MainColor,
                                            bg_color:_setting.BGColor,
                                            font_color:_setting.FontColor,
                                            persent_value: isNaN(item[header.code])?0:item[header.code]
                                        };
                                    }
                                } else if(_setting.ConditionType == 4){
                                    //大於等於 =
                                    if(item[header.code] >= _setting.ConditionValue){
                                        item[header.code+'_style'] = {
                                            main_color:_setting.MainColor,
                                            bg_color:_setting.BGColor,
                                            font_color:_setting.FontColor,
                                            persent_value: isNaN(item[header.code])?0:item[header.code]
                                        };
                                    }
                                } else if(_setting.ConditionType == 6){
                                    //小於等於
                                    if(item[header.code] <= _setting.ConditionValue){
                                        item[header.code+'_style'] = {
                                            main_color:_setting.MainColor,
                                            bg_color:_setting.BGColor,
                                            font_color:_setting.FontColor,
                                            persent_value: isNaN(item[header.code])?0:item[header.code]
                                        };
                                    }
                                } else if(_setting.ConditionType == 7){
                                    // 大於
                                    if(item[header.code] > _setting.ConditionValue){
                                        item[header.code+'_style'] = {
                                            main_color:_setting.MainColor,
                                            bg_color:_setting.BGColor,
                                            font_color:_setting.FontColor,
                                            persent_value: isNaN(item[header.code])?0:item[header.code]
                                        };
                                    }
                                } else if(_setting.ConditionType == 8){
                                    //小於
                                    if(item[header.code] < _setting.ConditionValue){
                                        item[header.code+'_style'] = {
                                            main_color:_setting.MainColor,
                                            bg_color:_setting.BGColor,
                                            font_color:_setting.FontColor,
                                            persent_value: isNaN(item[header.code])?0:item[header.code]
                                        };
                                    }
                                }
                                if(item[header.code+'_style'])
                                    break;
                            };
                        }
                    }
                }
                return item[header.code+'_style']||{};
            }

            //20200413 modify by Dustdusk for M#: 增加標籤注入
            function generateReportStyle(){
                if(_report_style == undefined){
                    _report_style = $('<style></style>').appendTo($('#report_content'));
                }
                var _style = '.kmi-list__header { font-size:' + _refresh.font_size + 'px; height: '+ (_refresh.font_size+22) + 'px; line-height: '+ (_refresh.font_size+22) + 'px; flex: 0 0 '+ (_refresh.font_size+22) + 'px;}';
                    _style += '.kmi-list__row-content .kmi-list__row { height:' + (_refresh.font_size+18) + 'px;}';
                    _style += '.kmi-list__row-content .kmi-list__row .kmi-list__column { font-size:' + _refresh.font_size + 'px; line-height: '+ (_refresh.font_size+6) + 'px;}';
                    _style += '.kmi-list__row-content .kmi-list__row .kmi-list__column .item-light { width:' + (_refresh.font_size+6) + 'px; height: '+ (_refresh.font_size+6) + 'px;}';
                    _style += '.kmi-list__row-content .kmi-list__row .kmi-list__column .item-bar { height: '+ (_refresh.font_size+6) + 'px;}';
                    _style += '.kmi-list__row-content .kmi-list__row .group__column {  font-size:' + _refresh.font_size + 'px; line-height: '+ (_refresh.font_size+6) + 'px;}';
                _report_style.html(_style);
            }

            //20210622 modify by Dustdusk for M#93707: C12增加支援外部系統 / 帆軟
            function showReport(url){
                $scope.$root.showLoading();
                let report_content = document.getElementById('report-outside-content');
                report_content.addEventListener('load', function(arg){
                    $scope.$root.hideLoading();
                });
                report_content.src= url;
            }
            // 20211222 add by Alan for M#0102882: 處理當排序值為null時，filter無法正常過濾的狀況
            function resetFilter(filter) {
                // 檢查過濾條件是否有空字串，有就替換成undefined
                // 這是要避免當清單有null值且過濾條件是空字串的時候，包含null值的列會被過濾掉
                for (let prop in filter) {
                    filter[prop] = filter[prop] === '' ? undefined : filter[prop];
                }
                return filter
            }
        }
];});
